<?php
/*
=================================================================
= Title: dispatch 
= Desc: Retrives requests from nabLib.js. Performs requests and returns json data
= Author: Adam Saxén
= Copywrite Nabton.com 2014
= Revision history: 
= 2014-07-14 - Added comments to library  
=================================================================
*/
error_reporting(E_ALL);
ini_set('display_errors', 'On');

//############# Variables ####################
$action    = $_GET['action'];
$ff        = $_GET['ff'];

//File path to data
$fp        = __DIR__.DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR."nabServer".DIRECTORY_SEPARATOR."data".DIRECTORY_SEPARATOR; 
$file_suffix = "nab";


//Switch statement to determine what action to perform
switch($action){

	case 'sel_data':
		$files = scandir($fp);
		$results = array();
		
		$mm1 = $file_suffix;
		$mm2 = 'data';
		$i = 0;
		foreach ($files as &$f) {
   		 	$pos1 = strpos($f,$mm1);
			$pos2 = strpos($f,$mm2);
			if($pos1 !== false && $pos2 !== false){
				
				$results[$i] = $f;
				$i = $i+1;
			}
		}
	break;
    
    case 'update_chart':
	    
		if ( $ff == 'a') {
			//Get current day file
			$files = scandir($fp);
			$resultsArr = array();
			
			$mm1 = $file_suffix;
			$mm2 = 'data';
			$i = 0;
			foreach ($files as &$f) {
				$pos1 = strpos($f,$mm1);
				$pos2 = strpos($f,$mm2);
				if($pos1 !== false && $pos2 !== false){
					
					$resultsArr[$i] = $f;
					$i = $i+1;
				}
			}
			$file =$resultsArr[count($resultsArr) - 1]; //Select latest file
		}
		else{
		 $file = $ff;
		}
		$length_data = 0;
		$dataArray = array();	
		$handle = fopen($fp.$file, "r");
		  if ($handle) {
			while (($line = fgets($handle)) !== false) {
				//echo("<p>$line</p>");
				$p = explode(" ", $line);
				//20 26 10 703.400 1  example data
				$time =  $p[0].":".$p[1].":".$p[2];
				$dataArray[] = array($time, (float)$p[3]);
			}
		  } else {
			echo("error");
		  } 
		  fclose($handle);
       
            $results = $dataArray; 
    
	break;
    
    

}

//Encode data to json 
echo json_encode($results); //Encode for json


?>
